import { useAtomValue } from "jotai";
import { memo, useEffect, useState } from "react";
import { Button, Modal, Table, Popconfirm } from "antd";
import { updateDeviceControl } from "@/lib/api/deviceStatus";
import getRequestErrorMessage from "@/lib/utils/getRequestErrorMessage";
import { useMessage } from "@/providers/AntdMessageProvider";
import { useDeviceContext } from "@/providers/DeviceProvider";
import { tokenAtom } from "@/store/user";
import type { IDeviceStatus } from "@/lib/types";

function ConfirmTaskControlDialog() {
  const { deviceList, reloadDeviceList } = useDeviceContext();
  const [data, setData] = useState<IDeviceStatus[]>(() => deviceList);

  useEffect(() => {
    setData(deviceList);
  }, [deviceList]);

  const confirmTakeControlList = data.filter(
    (device) => device.confirmTakeControl,
  );

  return (
    <Modal
      open={confirmTakeControlList.length > 0}
      title="请确认设备控制类型"
      footer={null}
      closable={false}
      width={800}
    >
      <Table
        dataSource={confirmTakeControlList}
        rowKey="deviceId"
        pagination={false}
        className="max-h-[70dvh] overflow-auto"
      >
        <Table.Column title="设备名称" dataIndex="deviceName" />
        <Table.Column
          title="操作"
          width={250}
          render={(row) => (
            <Actions
              device={row}
              onSuccess={() => {
                setData((p) =>
                  p.filter((device) => device.deviceId !== row.deviceId),
                );
                reloadDeviceList();
              }}
            />
          )}
        />
      </Table>
    </Modal>
  );
}

function Actions({
  device,
  onSuccess,
}: {
  device: IDeviceStatus;
  onSuccess: () => void;
}) {
  const [loading, setLoading] = useState(false);
  const [controlType, setControlType] = useState<"device" | "system">();
  const token = useAtomValue(tokenAtom);
  const message = useMessage();
  function handleUpdateDeviceControl(type: typeof controlType & {}) {
    setControlType(type);
    setLoading(true);
    updateDeviceControl({ deviceId: device.deviceId, controlType: type }, token)
      .then((res) => {
        if (res.code !== 200) throw res;
        setControlType(undefined);
        onSuccess();
      })
      .catch((error) => {
        setControlType(undefined);
        message.error(getRequestErrorMessage(error));
      })
      .finally(() => {
        setLoading(false);
      });
  }
  return (
    <div className="flex justify-evenly">
      <Popconfirm
        title={
          <span>
            修改设备控制类型为&nbsp;<strong>设备控制</strong>
          </span>
        }
        onConfirm={() => handleUpdateDeviceControl("device")}
        disabled={loading}
      >
        <Button type="primary" loading={controlType === "device" && loading}>
          设备控制
        </Button>
      </Popconfirm>
      <Popconfirm
        title={
          <span>
            修改设备控制类型为&nbsp;<strong>系统控制</strong>
          </span>
        }
        onConfirm={() => handleUpdateDeviceControl("system")}
        disabled={loading}
      >
        <Button type="primary" loading={controlType === "system" && loading}>
          系统控制
        </Button>
      </Popconfirm>
    </div>
  );
}

export default memo(ConfirmTaskControlDialog);
